import Cocoa
// 声明变量用 var
var greeting = "Hello, playground"
// 声明常量用 let
let CONSTANT = "Declare swift constant with let"
print(greeting + "\n" + CONSTANT)
// 简单数值
var myVariables = 42
myVariables = 50
let myConstant = 42
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble:Double = 70
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
// 字符串模板,使用 \()
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
// 多行文字,使用三个双引号 """
let quotation = """
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still have \(apples + oranges) pieces of fruit.
"""
// 数组和字典,允许结尾加逗号
var fruits = ["strawberries", "limes", "tangerines"]
// 修改数组中元素
fruits[0] = "grapes"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
fruits.append("bluebberries")
print(fruits)
// 声明空数组,空字典
let emtpyArray: [String] = []
let emtpyDictionary: [String: Float] = [:]
// 控制流
// 条件:if switch
// 循环:for-in while repeat-while
// 括号可选,大括号必须
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
print(score, teamScore)
}
print(teamScore)
// 记住 if 后面必须接受 Boolean 格式的表达式
let scoreDecoration = if teamScore > 10 {
"🎉"
} else {
""
}
print("Score:", teamScore, scoreDecoration)
// 空值的处理
var optionalString: String? /// 在值的类型后写一个问号 ( ? ),以将该值标记为可选
print(optionalString == nil)
// Prints "true"
optionalString = "hello"
print(optionalString == nil)
// Prints "false"
var optionalName: String? = "John Appleseed"
var greeting1 = "Hello!"
if let name = optionalName { // 判断可选空值是否有值
greeting1 = "Hello, \(name)"
}
print(greeting1)
// 默认值
// 处理可选值的另一种方法是使用 ?? 运算符提供默认值。如果缺少可选值,则改用默认值。
let nickname: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickname ?? fullName)"
// You can use a shorter spelling to unwrap a value, using the same name for that unwrapped value.
// 可以使用较短的拼写来解开值的包装,对该解包的值使用相同的名称。
if let nickname {
print("Hey, \(nickname)")
}
// Doesn't print anything, because nickname is nil.
// switch 支持 任何类型的数据 & 各种比较操作 - 它们不限于整数和相等性测试。
// 执行不会继续到下一个案例,因此无需在每个案例代码末尾显式断开开关(break)。
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
// for-in 迭代字典内容,无序
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (_, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
// while 循环
var n = 2
while n < 100 {
n *= 2
}
print(n)
// Prints "128"
// repeat-while/do-while 循环
var m = 2
repeat {
m *= 2
} while m < 100
print(m)
// Prints "128"
// 使用 ..< 创建边界开放的索引,使用 ... 创建闭合边界索引
var total = 0
for i in 0..<4 {
total += i
}
print(total)
// Prints "6"
//Use ..< to make a range that omits its upper value, and use ... to make a range that includes both values.
// Functions and Closures 函数和闭包
// 使用 -> 分割 参数名及其类型 & 函数的返回值类型
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")
// 默认情况下,函数把参数名称当做他们的 label 标签来使用,
// 可以在参数名称前边指定一个自定义的参数 标签 label ,或者用 _ 表示没有 label。
// 调用 func,传入参数时,通过 label 指定参数值
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")
// 元组
// 使用 tuple 元组来存储复合类型,
// 元组的内容可以通过 name 和 number 来访问
// 元组使用 小括号 来定义
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum) // 注意元组的顺序不能随意改变!
}
let statistics = calculateStatistics(scores: [3, 5, 100, 3, 9])
// 元组的内容可以通过 name 和 number 来访问
print(statistics.sum)
print(statistics.0)
print(statistics.1)
print(statistics.2)
// 局部函数
// 函数可以嵌套,嵌套函数可以访问上层作用域中的变量,
// 可以用嵌套函数复用代码
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
print(returnFifteen())
// 在 Swift 中函数是一等公民。
// 可以把函数作为返回值,使用括号表示函数类型
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
print(increment(7))
// 也可以把函数当做参数传给其他函数使用
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)
// 函数实际上就是一种闭包的特例
// 用大括号 {} 将代码括起来来编写匿名闭包。用于 in 将参数和返回类型与正文分开。
// {(arg: Int) -> Int in
// // todo
// }
var doubled_numbers = numbers.map({(number: Int) -> Int in
let result = 2 * number
return result
})
print(numbers, doubled_numbers)
// 闭包的简写方式:
// 类型一致,可以同时省略 参数和返回值的类型
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
// 通过数字而非名字来指代参数,在超短的闭包匿名函数中很好用。
// 作为函数 最后一个参数 的闭包,可以紧跟在括号后面出现
// 当闭包是函数的 唯一参数 时,可以完全 省略括号
let sortedNumbers = numbers.sorted { $0 > $1 } // 这里,省略了参数,直接使用数字参数正文;同时作为唯一参数,完全省略了括号
print(sortedNumbers)
// 更多来自 AIGC 例子说明闭包的简写方式:
// Swift中的闭包有多种简略写法,包括以下几种:
// 1. 尾随闭包:
// 当闭包是函数的最后一个参数时,可以将其写成尾随闭包。
// 这样可以将闭包的大括号移到函数调用的外部,使代码更加清晰简洁。
// 例如:
func someFunctionWithClosure(closure: () -> Void) {
// 函数体
}
// 不使用尾随闭包
someFunctionWithClosure(closure: {
// 闭包体
})
// 使用尾随闭包,这是是不是有点像 Javascript 中的函数声明?😄
someFunctionWithClosure() {
// 闭包体
}
// 2. 参数名称缩写:
// 当闭包的参数类型已知时,可以使用参数名称缩写来代替完整的参数名称。
// 使用$0、$1等来代表第一个、第二个参数,以此类推。
// 例如:
let numbers2 = [1, 2, 3, 4, 5]
// 不使用参数名称缩写
let mappedNumbers2 = numbers2.map({ (number: Int) -> Int in
return number * 2
})
// 使用参数名称缩写
let mappedNumbers2a = numbers2.map({ $0 * 2 })
// 3. 隐式返回:
// 当闭包只包含一行代码时,可以使用隐式返回来省略return关键字。
// 例如:
let numbers3 = [1, 2, 3, 4, 5]
// 不使用隐式返回
let mappedNumbers3 = numbers3.map({ (number: Int) -> Int in
return number * 2
})
// 使用隐式返回
let mappedNumbers3a = numbers3.map({ $0 * 2 })
// 4. 简化参数列表:
// 当闭包没有参数时,可以省略参数列表和in关键字。
// 例如:
// 不使用简化参数列表
let sayHello = { () -> Void in
print("Hello")
}
// 使用简化参数列表
let sayHello2 = {
print("Hello")
}
// Objects and Classes 对象和类
// 定义 - 类
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
// 实例化 - 类
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
print(shapeDescription)
// 构造函数
// 声明类时给定初始值,通过 init() 函数完成初始化设置
class NamedShape {
var numberOfSides: Int = 0
var name: String
// 构造函数
// 不允许有返回值
init(name: String) {
// 请注意如何使用 self 来区分属性 name 与参数 name
self.name = name
}
// 析构函数
// 不允许有入参
deinit {
self.name = "~"
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
// 子类继承父类,类不需要想 C# 中一样继承某个标准的根父类。
// 可以按需继承父类,或者完全不继承任何父类
// 子类重写父类方法时,必须要有 override 标记。
// 编译器会检查 override 缺失或多余的情况。
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name) // 通过 super.init 调用父类构造函数
numberOfSides = 4 // 直接给父类中定义的字段进行赋值
// init 不能有返回值
}
func area() -> Double {
return sideLength * sideLength
}
// 覆盖父类的方法
// 覆盖时一定要有 override,但是也不能多余。
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
print(test.area())
print(test.simpleDescription())
// getter 和 setter
class EquilateralTriangle: NamedShape { // 等边三角形
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
// 无返回值
}
// 周长 setter getter
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
// setter 中有名叫 newValue 的隐式参数。
// 也可以显式修改参数名称,例如: set newName {...}
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)
// willSet 和 didSet
// 如果不需要在 setter 中计算新值,仅仅执行一些逻辑,那么可以使用 willSet 和 didSet 来执行 sideEffect。
// 例如,以下例子确保三角形和正方形的边长始终相等
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
// Prints "10.0"
print(triangleAndSquare.triangle.sideLength)
// Prints "10.0"
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)
// Prints "50.0"
// 可选值
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
// 可以使用 ? 号访问,如果 ? 前是 nil,会忽略后续内容,整个表达式返回 nil
let sideLength = optionalSquare?.sideLength
// Enumerations and Structures 枚举和结构体
// 在 Swift 中,enum 可以有自己关联的方法。
enum Rank: Int { // 这里是 Int 类型,但是也可以使用字符串或浮点作为 raw type
case ace = 1 // 默认会从 0 开始,但是这里显式给定了原始值 1,后续值按顺序分配
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue
print(Rank.four, Rank.four.rawValue)
print(Rank.king, Rank.king.rawValue)
// 使用 init?(rawValue:) 初始化 enum 值,并指定 rawValue
// 如果 rawValue 匹配不到枚举有效值,会返回 nil
print(Rank(rawValue: -1)?.rawValue ?? "enum not matched")
print(Rank(rawValue: 10)?.rawValue ?? "enum not matched")
if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
}
// 例子
enum Suit {
case spades, hearts, diamonds, clubs
func simpleDescription() -> String {
switch self {
case .spades:
return "spades" // 黑桃,铁掀
case .hearts:
return "hearts" // 红心
case .diamonds:
return "diamonds" // 方片,钻石
case .clubs:
return "clubs" // 梅花,会员
}
}
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
// enum 的另一种用法
// 将 value 和 case 关联起来,而不是 raw value。
// 可以将关联的值视为类似于 enum 实例的存储属性。
enum ServerResponse {
case result(String, String)
case failure(String)
}
let success = ServerResponse.result("6:00 am", "8:09 pm") // 这里类似于把值存储在 enum 实例中了
let failure = ServerResponse.failure("Out of cheese.")
switch success {
case let .result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
print("Failure... \(message)")
}
// Prints "Sunrise is at 6:00 am and sunset is at 8:09 pm."
// struct 结构体
// 和 class 类似,比如 init,methods
// 最重要的区别点是,struct 是值传递,class 是引用传递
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())."
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
// todo
// 编写一个函数,该函数返回一个包含一副完整纸牌的数组,其中每张牌的等级和花色组合都有一张牌。
// Concurrency 并发
// 使用 async 标记异步函数,使用 await 标记调用的是异步函数。
// 这里跟 Javascript 完全一样 😄
func fetchUserID(from server: String) async -> Int {
if server == "primary" {
return 97
}
return 501
}
func fetchUsername(from server: String) async -> String {
let userID = await fetchUserID(from: server)
if userID == 501 {
return "John Appleseed"
}
return "Guest"
}
// 使用 async let 调用异步函数,使其并行执行。
// 使用 await 读取返回值。
// 与 Javascript 中的 Promise.all 相同 😄
func connectUser(to server: String) async {
async let userID = fetchUserID(from: server)
async let username = fetchUsername(from: server)
let greeting = await "Hello \(username), user ID \(userID)"
print(greeting)
}
// 在普通代码中使用 Task 调用异步函数,不会 block 代码执行
Task {
await connectUser(to: "primary")
}
// Protocols and Extension 协议和扩展
// 声明协议。
// 协议类似 Java 中的 interface 😄 ,实现协议 类似 实现接口
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust() // 类中无须 mutating 标记,struct 和 protocol 中需要 mutating 修饰
}
// class enum 和 struct 都可以 adopt 采用协议
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() { // 类中不需要用 mutating 标记,因为类的方法始终是可以修改自身的
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() { // struct 中需要用 mutating 标记
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
// extension 扩展
// 使用 extension 向现有的类型添加功能,比如扩展新方法和计算属性。
// 可以扩展其他地方声明的类型,甚至第三方库中引入的类型
extension Int: ExampleProtocol {
// 使用 extension 扩展了 Int 类型,增加了 protocol 协议
var simpleDescription:String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
// todo
// Write an extension for the Double type that adds an absoluteValue property.
// 可以像使用 type 一样使用协议,例如创建一系列符合单个协议的对象。
// 但是除了协议外的方法和属性将不再能访问,这里与 Javascript 不同 😄
let protocolValue: any ExampleProtocol = a
// 尽管 a 本来是 SimpleClass 创建出来的,但是编译器也会讲起视为 ExampleProtocol 类型,所以除了协议中定义的方法和属性外,不能再访问其他属性、方法。
print(protocolValue.simpleDescription)
// Prints "A very simple class. Now 100% adjusted."
// print(protocolValue.anotherProperty) // Uncomment to see the error,尽管是在 SimpleClass 中定义过的
// Error Handling 错误处理
// 可以通过 adopt Error protocol 协议的任何类型来表示错误
enum PrinterError: Error {
case outOfPaper
case noToner
case onFire
}
// 使用 throws 标记可能抛出错误的函数
// 使用 throw 抛出错误
func send(job: Int, toPrinter printerName: String) throws -> String {
if printerName == "Never Has Toner" {
throw PrinterError.noToner
}
return "Job sent"
}
// 使用 do-catch 处理错误。
do {
let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")
print(printerResponse)
} catch {
print(error) // 自动命名为 error,也可以自己指定
}
// 多重 catch case
// 使用多重 catch 块处理特定错误,就像使用 case 块一样
do {
let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
print(printerResponse)
} catch PrinterError.onFire {
print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
print("Printer error: \(printerError).")
} catch {
print(error)
}
// try? 将执行结果转换为可选。如果函数执行发生错误,丢弃特定错误,结果返回 nil
let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")
print(printerSuccess, printerFailure)
// defer 代码块
// 在函数所有代码执行后,但是未返回值的时候执行。使用 defer 可以设置清理代码。
// 无论是否有 Error 抛出,都会执行 defer
var fridgeIsOpen = false
let fridgeContent = ["milk", "eggs", "leftovers"]
func fridgeContains(_ food: String) -> Bool {
fridgeIsOpen = true
defer { // 执行结束后清理状态
fridgeIsOpen = false
}
let result = fridgeContent.contains(food)
return result
}
fridgeContains("banana")
print(fridgeIsOpen)
// Generics 泛型
// 在尖括号中间写一个名称,<Item> 表示创建泛型函数或类型
func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
var results: [Item] = []
for _ in 0..<numberOfTimes {
results.append(item)
}
return results
}
let results = makeArray(repeating: "knock", numberOfTimes: 3)
print(results)
// 使用泛型创建:函数,类,枚举和结构体
// 例如,重新实现 Swift 标准库的 optional type
enum OptionalValue<Wrapped> {
case none
case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(42)
// 使用 where 来要求泛型类型必须满足条件
// 例如,必须实现协议、要求两个类型相同,或者要求类具有特定的超类
// <T: Equatable> 也可以写成 <T> ... where T: Equatable
// lhs: left-hand side 左手边
// rhs: right-hand side 右手边
func anyCommonElements<T: Sequence, U:Sequence>(_ lhs: T, _ rhs: U) -> Bool where T.Element: Equatable, T.Element == U.Element {
for lhsItem in lhs {
for rhsItem in rhs {
if(lhsItem == rhsItem) {
return true
}
}
}
return false
}
anyCommonElements([1,2,3], [3])